/****************************************************************
 * Copyright (c) 2006-2007 Besture All Rights Reserved.
 * 
 * File Name:		PageController.cs
 * 
 * Created:		2013/06/24
 * Original Author:	Hongwei Zhao 
 * 
 * ------------------------------------------------------------
 * MODIFICATION HISTORY
 * ------------------------------------------------------------
 * When			Who		Why
 * ------------------------------------------------------------
 * 
 *
 ****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Collections;
using Besture.Common.PageControl.Script;
using Besture.Common.Definition;


namespace Besture.Common.PageControl
{
    /// <summary>
    /// Page controller class
    /// </summary>
    public class PageController
    {
        private Hashtable hashParameter;
        private Hashtable hashQueryParameter;
        private Page currentPage;
        private string csTargetPageId;

        ///<summary>
        /// Set Target Page ID
        ///</summary>
        public void SetTargetPageID(string sPageID)
        {
            csTargetPageId = sPageID;
        }
        ///<summary>
        /// Clear the parameters of the current page from session
        ///</summary>
        public PageController(Page page)
        {
            hashParameter = new Hashtable();
            hashQueryParameter = new Hashtable();
            this.currentPage = page;
        }
        ///<summary>
        /// Clear the parameters of the current page from session
        ///</summary>
        ///<remarks></remarks>
        public void ClearParameter(Page currentPage)
        {
            IEnumerator enumerator = currentPage.Session.Keys.GetEnumerator();
            ArrayList listDeletingKeys = new ArrayList();
            while (enumerator.MoveNext())
            {
                string current = enumerator.Current.ToString();
                if (current.StartsWith(this.GetPageId(currentPage.Request.Url.OriginalString)))
                {
                    listDeletingKeys.Add(current);
                }                
            }
            IEnumerator enumerator1 = listDeletingKeys.GetEnumerator();
            while (enumerator1.MoveNext())
            {
                currentPage.Session.Remove(enumerator1.Current.ToString());
            }
        }
        ///<summary>
        /// Remove the parameter of the current page from session
        ///</summary>
        ///<param name="strKey">key</param>
        ///<remarks></remarks>
        public void RemoveParameter(string strKey)
        {
            currentPage.Session.Remove(this.GetPageId(currentPage.Request.Url.OriginalString)+"_"+strKey);
        }

        ///<summary>
        /// Transfer to the error page.
        ///</summary>
        ///<remarks></remarks>
        public void ToErrorPage()
        {
            HttpContext.Current.Response.Redirect(AppSettings.GetErrorPage(), false);
            this.AddParameterToSession(this.GetPageId(AppSettings.GetErrorPage()));
        }
        ///<summary>
        /// Transfer to the error page.
        ///</summary>
        ///<param name="strErrorId">Error Id</param>
        ///<remarks></remarks>
        public void ToErrorPage(string strErrorId)
        {
            HttpContext.Current.Response.Redirect(AppSettings.GetErrorPage(), false);
            this.AddParameter(Constants.KEY_ERROR_ID, strErrorId);
            this.AddParameterToSession(this.GetPageId(AppSettings.GetErrorPage()));
        }
        ///<summary>
        /// Transfer to the specific url.
        ///</summary>
        ///<param name="strPageId">Next page url</param>
        ///<param name="intWith">Width of dialog</param>
        ///<param name="intHeight">Height of dialog</param>
        ///<remarks></remarks>
        public void Transfer(string strPageId)
        {
            this.currentPage.Response.Redirect(PageManager.getPage(strPageId).Path + this.GetQueryString(), false);            
            this.ClearParameter(this.currentPage);
            this.AddParameterToSession(strPageId);
        }
        ///<summary>
        /// Show the url in a modal dialog width the specific with and height.
        ///</summary>
        ///<param name="strNextPage">Next page url</param>
        ///<param name="intWith">Width of dialog</param>
        ///<param name="intHeight">Height of dialog</param>
        ///<remarks></remarks>
        public void ShowModalDialog(string strPageId, int intWith, int intHeight)
        {
            string strScript = ScriptUtil.GetOpenModalDialogScript(PageManager.getPage(strPageId).Path + this.GetQueryString(), intWith, intHeight);
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "ShowModalDialog", strScript.ToString());
            this.AddParameterToSession(strPageId);
            
        }

        ///<summary>
        /// Show the url in a modal dialog width the specific with and height.
        ///</summary>
        ///<param name="strNextPage">Next page url</param>
        ///<param name="intWith">Width of dialog</param>
        ///<param name="intHeight">Height of dialog</param>
        ///<remarks></remarks>
        public void ShowModalDialog(string strPageId, int intWith, int intHeight, bool lbNeed)
        {
            string strScript = ScriptUtil.GetModalDialogScript(PageManager.getPage(strPageId).Path + this.GetQueryString(), intWith, intHeight, lbNeed);
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "ShowModalDialog", strScript.ToString());
            this.AddParameterToSession(strPageId);
        }

        ///<summary>
        /// Show the url in a modeless dialog with the specific width and height.
        ///</summary>
        ///<param name="strNextPage">Next page url</param>
        ///<param name="intWith">Width of dialog</param>
        ///<param name="intHeight">Height of dialog</param>
        ///<remarks></remarks>
        public void ShowModelessDialog(string strPageId, int intWith, int intHeight)
        {
            string strScript = ScriptUtil.GetOpenModelessDialogScript(PageManager.getPage(strPageId).Path, intWith, intHeight);
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "ShowModelessDialog", strScript.ToString());
            this.AddParameterToSession(strPageId);
        }

        ///<summary>
        /// Show the url in a modeless dialog with parameters.
        ///</summary>
        ///<param name="strNextPage">Next page url</param>
        ///<param name="strParameter">Url Parameters</param>
        ///<remarks></remarks>
        public void ShowModelessDialog(string strPageId, string strParameter)
        {
            strParameter = strParameter == string.Empty ? string.Empty : "?" + strParameter;
            string strScript = ScriptUtil.GetOpenModelessDialogScript(PageManager.getPage(strPageId).Path + strParameter);
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "ShowModelessDialog", strScript.ToString());
        }

        /// <summary>
        /// Show PreviewDialog
        /// </summary>
        /// <param name="strLang">Language</param>
        /// <param name="strRootSource">RootSource</param>
        public void ShowPreviewDialog(string strLang, string strRootSource)
        {
            string strParameter = "?";
            if (strLang != string.Empty)
            {
                strParameter += "Button_cn=" + strLang;
            }
            if (strRootSource != string.Empty)
            {
                if (strLang != string.Empty)
                {
                    strParameter += "&";
                }
                strParameter += "RootSource=" + strRootSource;
            }
            string strScript = "MM_openBrWindow('../Resume/ResumePreview.aspx" + strParameter + "','resume_preview','toolbar=no,scrollbars=yes,resizable=yes,width=680,height=820')";
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "ShowPreviewDialog", strScript, true);
        }

        ///<summary>
        /// add the parameter  to next page with the key
        ///</summary>
        ///<param name="strKey">key</param>
        ///<param name="obj">Parameter Object</param>
        ///<remarks></remarks>
        public void AddParameter(string strKey,object obj)
        {
            if (!hashParameter.ContainsKey(strKey))
            {
                hashParameter.Add(strKey, obj);
            }
            else
            {
                hashParameter.Remove(strKey);
                hashParameter.Add(strKey, obj);
            }
        }
        ///<summary>
        /// get the parameter with the key
        ///</summary>
        ///<param name="strKey">key</param>
        ///<remarks></remarks>
        public object GetParameter(string strKey)
        {
            string strPageId = this.GetPageId(this.currentPage.Request.Url.OriginalString);
            object objValue = this.currentPage.Session[strPageId + "_" + strKey];
            return objValue;
        }
        ///<summary>
        /// add the query parameter  to next page with the key.
        ///</summary>
        ///<param name="strKey">key</param>
        ///<param name="obj">Parameter Object</param>
        ///<remarks></remarks>
        public void AddQueryParameter(string strKey, string obj)
        {
            hashQueryParameter.Add(strKey, obj);
        }
        ///<summary>
        /// get the query parameter with the key
        ///</summary>
        ///<param name="strKey">key</param>
        ///<remarks></remarks>
        public string GetQueryParameter(string strKey)
        {

            string strValue = this.currentPage.Request.QueryString.Get(strKey);
            return strValue;
        }
        ///<summary>
        /// get page id with the specific url
        ///</summary>
        ///<param name="strUrl">Url</param>
        ///<remarks></remarks>
        public string GetPageId(string strUrl)
        {
            int intStart = strUrl.LastIndexOf("/") + 1;
            int intEnd = strUrl.LastIndexOf(".aspx");
            string strValue = strUrl.Substring(intStart, intEnd - intStart);
            return strValue;
        }

        private void AddParameterToSession(String nextPageId)
        {
            int intCount = hashParameter.Keys.Count;
            IDictionaryEnumerator enumerator = hashParameter.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (currentPage.Session[nextPageId + "_" + enumerator.Key] == null)
                {
                    this.currentPage.Session.Add(nextPageId + "_" + enumerator.Key, enumerator.Value);
                }
                else
                {
                    this.currentPage.Session.Remove(nextPageId + "_" + enumerator.Key);
                    this.currentPage.Session.Add(nextPageId + "_" + enumerator.Key, enumerator.Value);
                }
            }
        }
        private string GetQueryString()
        {
            string strValue = "";
            int i = 0 ;
            int intCount = hashQueryParameter.Keys.Count;
            IDictionaryEnumerator enumerator = hashQueryParameter.GetEnumerator();
            
            while (enumerator.MoveNext())
            {
                if (i == 0)
                {
                    strValue += "?";
                }
                strValue += enumerator.Key + "=" + this.currentPage.Server.HtmlEncode(enumerator.Value.ToString());
                if (i != intCount - 1){
                        strValue = strValue + "&";
                }    
                i ++;
            }

            
            return strValue;
        }
        ///<summary>
        /// Show the url in a modal dialog width the specific with and height.
        ///</summary>
        ///<remarks></remarks>
        public void CloseModalDialog(String returnValue)
        {
            string strScript = ScriptUtil.GetCloseModalDialogScript(returnValue);
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "CloseModalDialog", strScript.ToString());
            this.RemoveParameter(this.GetPageId(currentPage.Request.Url.OriginalString));
            if ((csTargetPageId != "") && hashParameter.Count > 0)
            {
                this.AddParameterToSession(csTargetPageId);
            }
        }
        ///<summary>
        /// Show the url in a modal dialog width the specific with and height.
        ///</summary>
        ///<remarks></remarks>
        public void CloseModalDialog()
        {
            this.CloseModalDialog("");
        }
        ///<summary>
        /// Show the url in a modal dialog width the specific with and height.
        ///</summary>
        ///<remarks></remarks>
        public void CloseModelessDialog()
        {
            string strScript = ScriptUtil.GetCloseModelessDialogScript();
            this.currentPage.ClientScript.RegisterStartupScript(typeof(string), "CloseModelessDialog", strScript.ToString());
            this.RemoveParameter(this.GetPageId(currentPage.Request.Url.OriginalString));
            if ((csTargetPageId != "") && hashParameter.Count > 0)
            {
                this.AddParameterToSession(csTargetPageId);
            }
        }
        
    }
}
